<template>
  <page-wrap>
    <search-wrap
      :schema="searchSchema"
      @reset="setSearchParams"
      @search="setSearchParams"
    />
    <div class="mb-10px">
      <a-button type="primary" @click="addAction">新增</a-button>
    </div>
    <table-wrap
      :columns="tableColumns"
      :data="dataList"
      :pagination="pagination"
      :loading="loading"
      @register="tableRegister"
    />
  </page-wrap>

  <modal-dialog
    v-model="dialogAddVisible"
    title="新增"
    width="460"
    :fullscreen="false"
  >
    <AddForm ref="addFormRef" />
    <template #footer>
      <a-button type="primary" :loading="saveLoading" @click="save">
        保存
      </a-button>
      <a-button @click="dialogAddVisible = false">关闭</a-button>
    </template>
  </modal-dialog>

  <modal-dialog
    v-model="dialogEditVisible"
    title="编辑"
    width="460"
    :fullscreen="false"
  >
    <EditForm ref="editFormRef" :current-id="currentId" />
    <template #footer>
      <a-button type="primary" :loading="saveLoading" @click="update">
        保存
      </a-button>
      <a-button @click="dialogEditVisible = false">关闭</a-button>
    </template>
  </modal-dialog>

  <a-drawer
    :width="560"
    :visible="moduleDrawerVisible"
    :mask-closable="false"
    :unmount-on-close="true"
    @cancel="moduleDrawerVisible = false"
  >
    <template #title>权限配置</template>
    <ModuleForm ref="moduleFormRef" :current-id="currentId" />
    <template #footer>
      <a-button @click="moduleDrawerVisible = false">关闭</a-button>
      <a-button type="primary" :loading="saveLoading" @click="updateModule">
        保存
      </a-button>
    </template>
  </a-drawer>
</template>
<script setup lang="tsx">
  import { Link } from '@arco-design/web-vue';

  import {
    listApi,
    saveApi,
    updateApi,
    updateModuleApi,
    removeApi,
  } from '@/api/system/role';
  import type { RoleVO } from '@/api/system/role/types';
  import { useTable } from '@/hooks/table';
  import { useDictStore } from '@/store';

  import AddForm from './components/add-form.vue';
  import EditForm from './components/edit-form.vue';
  import ModuleForm from './components/module-form.vue';

  const dictStore = useDictStore();

  const { tableRegister, tableState, tableMethods } = useTable({
    fetchDataApi: async () => {
      const { pageParams } = tableState;
      return await listApi({
        ...pageParams.value,
        ...unref(searchParams),
      });
    },
    fetchDelApi: async () => {
      const res = await removeApi(unref(currentId));
      return !!res;
    },
  });

  const { dataList, loading, pagination } = tableState;
  const { getList, delList } = tableMethods;

  const tableColumns = reactive<TableColumn[]>([
    {
      field: 'index',
      title: '序号',
      type: 'index',
    },
    {
      field: 'code',
      title: '编码',
    },
    {
      field: 'name',
      title: '名称',
    },
    {
      field: 'remark',
      title: '备注',
    },
    {
      field: 'action',
      title: '操作',
      width: 200,
      render: (data: any) => {
        const row = data.record as RoleVO;
        return (
          <>
            <Link onClick={() => editAction(row.id)}>编辑</Link>
            <Link onClick={() => delAction(row.id)}>删除</Link>
            <Link
              disabled={canSetRole(row.code)}
              onClick={() => setModuleAction(row.id)}
            >
              权限配置
            </Link>
          </>
        );
      },
    },
  ]);

  const searchSchema = reactive<FormSchema[]>([
    {
      field: 'name',
      label: '名称',
      type: 'Input',
    },
  ]);

  const searchParams = ref({});
  const setSearchParams = (data: any) => {
    searchParams.value = data;
    getList(false);
  };

  const canSetRole = (code: string) => {
    return dictStore.getItems('DefaultRole')?.some((item) => {
      return item.extend.code === code && !item.extend.canSet;
    });
  };

  const currentId = ref<string>();

  const dialogAddVisible = ref(false);
  const dialogEditVisible = ref(false);
  const moduleDrawerVisible = ref(false);

  const addFormRef = ref<ComponentRef<typeof AddForm>>();
  const editFormRef = ref<ComponentRef<typeof EditForm>>();
  const moduleFormRef = ref<ComponentRef<typeof ModuleForm>>();

  const saveLoading = ref(false);

  // 新增角色
  const addAction = () => {
    currentId.value = undefined;
    dialogAddVisible.value = true;
  };

  const save = async () => {
    const addForm = unref(addFormRef);
    const formData = await addForm?.submit();
    if (formData) {
      saveLoading.value = true;
      let result = false;
      try {
        const res = await saveApi(formData as RoleVO);
        result = !!res;
        if (result) {
          getList(false);
          dialogAddVisible.value = false;
        }
      } catch (error) {
        console.log(error);
      } finally {
        saveLoading.value = false;
      }
    }
  };

  // 编辑角色
  const editAction = (id: string) => {
    currentId.value = id;
    dialogEditVisible.value = true;
  };

  const update = async () => {
    const editForm = unref(editFormRef);
    const formData = await editForm?.submit();
    if (formData) {
      saveLoading.value = true;
      let result = false;
      try {
        const res = await updateApi(formData as RoleVO);
        result = !!res;
        if (result) {
          getList();
          dialogEditVisible.value = false;
        }
      } catch (error) {
        console.log(error);
      } finally {
        saveLoading.value = false;
      }
    }
  };

  // 删除角色
  const delAction = async (id: string) => {
    currentId.value = id;
    await delList(1);
  };

  // 设置菜单权限
  const setModuleAction = (id: string) => {
    currentId.value = id;
    moduleDrawerVisible.value = true;
  };

  const updateModule = async () => {
    const moduleForm = unref(moduleFormRef);
    const moduleIds: any = await moduleForm?.submit();
    saveLoading.value = true;
    let result = false;
    try {
      const res = await updateModuleApi(
        currentId.value,
        moduleIds.webModuleIds
      );
      result = !!res;
      if (result) {
        MessageInfo.success();
        getList();
        moduleDrawerVisible.value = false;
      }
    } catch (error) {
      console.log(error);
    } finally {
      saveLoading.value = false;
    }
  };
</script>
